import hashlib
import random
import re, time

from app import sql
from app.models.model import User
from . import uitl_blu
from flask import render_template, request, jsonify, session, make_response, redirect, url_for
from app.util.capt.captcha import captcha
from werkzeug.security import generate_password_hash, check_password_hash
from app.util.email import send_email
from multiprocessing import Process

# 图片验证码
@uitl_blu.route("/image_code")
def image_code():
    """
    生成图片验证码
    :return:
    """
    # 调用函数，生成图片验证码
    _, code_str, code_img = captcha.generate_captcha()
    session["vercode"] = code_str
    return code_img


@uitl_blu.route("/getUser")
def getUser():
    user_name = session.get("user_name")
    pwd = session.get("password")
    print(user_name, pwd, "aaa")
    if user_name and pwd:
        return "fewafe"
    """"""
    return ""


# 登录
@uitl_blu.route("/login", methods=["POST", "GET"])
def user_log():
    if request.method == "GET":
        return render_template("user/login.html", a=0)
    email = request.form.get("email")
    pwd = request.form.get("pass")
    vercode = request.form.get("vercode")
    ret = {"status": 0, "msg": "正在登陆"}
    if not vercode:
        ret["status"], ret["msg"] = 4004, "缺少验证码"
        return jsonify(ret)
    if session.get("vercode").lower() != vercode.lower():
        ret["status"], ret["msg"] = 4005, "验证码错误"
        return jsonify(ret)
    a = sql.session.query(User).filter(User.email == email).first()
    if not a:
        ret["status"], ret["msg"] = 4006, "邮箱账号或密码错误"
        return jsonify(ret)
    if not check_password_hash(a.password_hash, pwd):
        ret["status"], ret["msg"] = 4007, "邮箱账号或密码错误"
        return jsonify(ret)
    session["user_email"] = a.email
    session["user_name"] = a.nick_name
    return jsonify(ret)


# 注册
@uitl_blu.route("/reg", methods=["POST", "GET"])
def reg():
    if request.method == "GET":
        return render_template("user/reg.html")
    emali = request.form.get("email")
    user_name = request.form.get("username")
    pwd1 = request.form.get("pass")
    pwd2 = request.form.get("repass")
    vercode = request.form.get("vercode")
    ret = {"status": 4009, "msg": "注册成功"}
    if not all([emali, user_name, pwd2, pwd1, vercode]):
        ret["msg"] = "缺少数据，注册失败"
        return jsonify(ret)
    if not user_name.isalnum():
        ret["msg"] = "用户名必须是数字或字母组合，不能有特殊符号"
        return jsonify(ret)
    if not re.search("\w{5,20}@(163|qq|126)\.com$", emali):
        ret["msg"] = "邮箱错误,请输入正确的邮箱"
        return jsonify(ret)
    if session.get("vercode").lower() != vercode.lower():
        ret["status"], ret["msg"] = 4005, "验证码错误"
        return jsonify(ret)
    if pwd2 == pwd1:
        if 6 <= len(pwd1) <= 16:
            pass
        else:
            ret["msg"] = "密码必须在6位到16位之间"
            return jsonify(ret)
    else:
        ret["msg"] = "两次密码不一样"
        return jsonify(ret)
    a = sql.session.query(User).filter(User.email == emali).first()
    if a:
        ret["msg"] = "注册失败，该邮箱已被注册"
        return jsonify(ret)
    b = sql.session.query(User).filter(User.nick_name == user_name).first()
    if b:
        ret["msg"] = "该用户名已被使用， 请更换用户名后重新注册"
        return jsonify(ret)

    user = User()
    user.email = emali
    user.nick_name = user_name
    user.password_hash = generate_password_hash(pwd1)
    user.avatar_url = "//thirdqq.qlogo.cn/qqapp/101235792/65423A7AA41D58E7E801C3AB6821F1B7/100"
    token = hashlib.md5()
    token.update((str(time.time()) + str(random.randint(999, 999999)) + emali).encode("utf-8"))
    user.activate = token.hexdigest()
    sql.session.add(user)
    sql.session.commit()
    session["user_email"] = user.email
    session["user_name"] = user.nick_name
    ret["status"] = 0
    # 此时进行数据库数据添加操作
    fs_email = send_email.Email()
    p = Process(target=fs_email.run, args=(user_name, user.activate, emali))
    p.start()
    return jsonify(ret)


# 忘记密码
@uitl_blu.route("/forget", methods=["POST", "GET"])
def forget():
    if request.method == "GET":
        return render_template("user/forget.html")
    emali = request.form.get("email")
    vercode = request.form.get("vercode")

    if session.get("vercode").lower() != vercode.lower():
        ret = {"status": 4005, "msg": "验证码错误"}
        return jsonify(ret)

    a = sql.session.query(User).filter(User.email == emali).first()
    if not a:
        ret = {"status": 4005, "msg": "该用户不存在"}
        return jsonify(ret)
    token = hashlib.md5()
    token.update((str(time.time()) + str(random.randint(999, 999999)) + emali).encode("utf-8"))
    a.forget = token.hexdigest()
    sql.session.commit()
    re_pass_email = send_email.repass
    p = Process(target=re_pass_email.run, args=(a.nick_name, a.forget, emali))
    p.start()
    ret = {"status": "0", "msg": "找回邮件已发送，请到邮箱内进行密码重设"}
    return jsonify(ret)


@uitl_blu.route("/api/activate/", methods=["GET", "POST"])
def activate():
    user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    if user:
        if user.activate != "0":
            fs_email = send_email.Email()
            p = Process(target=fs_email.run, args=(user.nick_name, user.activate, user.email))
            p.start()
            ret = {"status": 0, "msg": "发送成功"}
            return jsonify(ret)
        ret = {"status": "9005", "msg": "已激活"}
        return jsonify(ret)
    return redirect(url_for("uitl_blu.user_log"))
